package com.it.you.base.list;

import com.it.you.pojo.Worker;
import lombok.SneakyThrows;
import org.assertj.core.util.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListTest2 {

    @SneakyThrows
    public static void main(String[] args) {
        ArrayList<Worker> list = new ArrayList<>();
        //System.out.println(list.get(0));//会报错

        Worker worker1 = new Worker("Tom", 20, Arrays.asList("篮球", "足球", "排球"));

        Worker worker2 = new Worker("Jack", 18, Arrays.asList("台球", "乒乓球"));
        Worker worker3 = new Worker("Baby", 16, Arrays.asList("棒球", "足球"));
        Worker worker4 = new Worker("Mom", 30, Arrays.asList("橄榄球", "排球"));
        list.add(worker1);
        list.add(worker2);
        list.add(worker3);
        list.add(worker4);

        a:
        for (Worker worker : list) {
            System.out.println(worker);
            for (String hobby : worker.getHobbies()) {
                System.out.println(hobby);
                if (hobby.contains("篮球")) {
                    System.out.println("找到篮球爱好者");
                    break a; //双层for循环使用标记跳出外层循环 a
                }
            }
        }

        List list1 = handlePage(list, 1, 2);
        System.out.println("===" + list1 + "===");
    }

    /**
     * 内存分页
     *
     * @param list
     * @param pageNum
     * @param pageSize
     * @return
     */
    public static List handlePage(List list, int pageNum, int pageSize) {
        if (CollectionUtils.isEmpty(list)) {
            return Lists.emptyList();
        }
        // 记录总数
        int count = list.size();
        // 页数
        int pageCount = 0;
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        // 开始索引
        int fromIndex = 0;
        // 结束索引
        int toIndex = 0;
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        return list.subList(fromIndex, toIndex);
    }
}
